<?php
/**
 * Created by PhpStorm.
 * User: cth
 * Date: 2017/6/13
 * Time: 上午10:13
 */

namespace App\Repositories;

use App\Models\CashConfig;
use App\Models\OrderQueue;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\Order;
use App\Models\Shop;
use App\Models\Cash;
use App\Models\CapitalRecord;
use App\Models\ShopRoomTable;
use App\Models\WeixinUser;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Tools\MoneyChange;

class UserRepository
{
    protected $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    //个人中心
    public function userMessage($request)
    {
        //小程序
        $token = $request->token;
        if($token){
            $WeixinUser = WeixinUser::where('token',$token)->first();
            if($WeixinUser){
                $user_id = $WeixinUser['user_id'];
            }else{
                return show(202,'用户不存在');
            }
            //web端
        }else {
            $user_id = Auth::id();
            if (!$user_id) {
                return show(201, '未登录');
            }
        }
        $data = User::with('UserInfo')
            ->with('defaultAddresses')
            ->with('shopApply')
            ->where('id',$user_id)
            ->get();

        return show(200,'ok',$data);
    }

    //更改用户信息(头像、昵称、性别)
    public function updateUserMessage($request)
    {
        $request = $request->toArray();
        $user_id = Auth::id();
        $data = User::where('id',$user_id)->update($request);
        if($data)
        {
            return show(200,'ok');
        }
            return show(201,'fail');
    }

    //账单明细
    public function account($token)
    {
        //小程序
        if($token){
            $WeixinUser = WeixinUser::where('token',$token)->first();
            if($WeixinUser){
                $user_id = $WeixinUser['user_id'];
            }else{
                return show(202,'用户不存在');
            }
            //web端
        }else {
            $user_id = Auth::id();
            if (!$user_id) {
                return show(201, '未登录');
            }
        }
        $data = CapitalRecord::where('user_id',$user_id)
            ->orderBy('created_at','desc')
            ->get();
        if(!$data->isEmpty())
        {
            return show(200,'ok',$data);
        }
            return show(201,'empty');
    }

    //账单详情
    public function accountDetail($request)
    {
        $id = $request->id;
        $data = CapitalRecord::find($id);
        if($data)
        {
            return show(200,'ok',$data);
        }
            return show(201,'false');
    }

    //我的订单
    public function getMyOrder($request)
    {
        try{
            $limit= $request->limit;
            $token = $request->token;
            //小程序
            if($token){
                $WeixinUser = WeixinUser::where('token',$token)->first();
                if($WeixinUser){
                    $user_id = $WeixinUser->user_id;
                }else{
                    return show(202,'用户不存在');
                }
                //web端
            }else {
                $user_id = Auth::id();
                if (!$user_id) {
                    return show(201, '未登录');
                }
            }
            $type = $request->type;
            if (!empty($type)){
                if (!in_array($type,['-1','0','1','2','3','4'])){
                    return show(201,'订单类型有误');
                }
            }

            if(empty($type)){
                $data = Order::with('Shop')
                    ->where('user_id',$user_id)
                    ->whereIn('order_type',['0','1','2','3'])    //   	订单类型(0外卖,1预定 ,2排队 ,3扫码 ,4直接付款 ,5充值)
                    ->orderBy('created_at','desc')
                    ->paginate($limit);
            }elseif ($type=='-1'){
                $data = Order::with('Shop')
                    ->where('user_id',$user_id)
                    ->whereIn('order_type',['0','1','2','3'])
                    ->where('order_status','<','0')
                    ->orderBy('created_at','desc')
                    ->paginate($limit);
            }else{
                $data = Order::with('Shop')
                    ->where('user_id',$user_id)
                    ->whereIn('order_type',['0','1','2','3'])
                    ->where('order_status',$type)
                    ->orderBy('created_at','desc')
                    ->paginate($limit);
            }
            if($data->isEmpty())
            {
                return show(202,'empty');
            }
            return show(200,'ok',$data);
        }catch (\Exception $e){
            return show(202,'empty');
        }

    }

    //订单详情
    public function orderDetail($request)
    {
        //小程序
        if($request->token){
            $WeixinUser = WeixinUser::where('token',$request->token)->first();
            if($WeixinUser){
                $user_id = $WeixinUser['user_id'];
            }else{
                return show(202,'用户不存在');
            }
            //web端
        }else {
            $user_id = Auth::id();
            if (!$user_id) {
                return show(201, '未登录');
            }
        }
        //预定订单
        if($request['order_type']==1){
            $data = Order::with('orderReserve')
                ->with('Shop')
                ->with('OrderDetail')
                ->with('invitation')
                ->where('id',$request['id'])
                ->first();
            if(empty($data)){
                return show(201,'fail');
            }else{
                $data = $data->toArray();
            }
            $RD = explode('|',$data['order_reserve']['desk_room']);
            if(empty($RD[0])){
                $roomDesk = null;
            }else {
                foreach ($RD as $key => $value) {
                    $roomDesk[] = ShopRoomTable::RoomTableFirst($value);
                }
            }
            $data['room_table'] = $roomDesk;
            //多规格
            foreach ($data['order_detail'] as $key => $value){
                if($data['order_detail'][$key]['is_attr']==1) {
                    $spec = explode(',', $data['order_detail'][$key]['spec']);
                    foreach ($spec as $k => $v) {
                        $spec2[$k] = explode('|', $spec[$k]);
                    }
                    $spec3 = '';
                    for ($i = 0; $i < count($spec2); $i++) {
                        $spec3 = $spec3 . '-' . $spec2[$i][0];
                    }
                    $spec3 = substr($spec3, 1);
                    $data['order_detail'][$key]['spec'] = $spec3;
                }
            }
        }

        //外卖和扫码订单
        if($request['order_type']==0 || $request['order_type']==3){
            $data = Order::with('Shop')
                ->with('ShopInfo')
                ->with('OrderDetail')
                ->with('orderscan')
                ->where('id',$request['id'])
                ->first();
            if(empty($data)){
                return show(201,'fail');
            }else{
                $data = $data->toArray();
            }
            //多规格
            foreach ($data['order_detail'] as $key => $value){
                if($data['order_detail'][$key]['is_attr']==1) {
                    $spec = explode(',', $data['order_detail'][$key]['spec']);
                    foreach ($spec as $k => $v) {
                        $spec2[$k] = explode('|', $spec[$k]);
                    }
                    $spec3 = '';
                    for ($i = 0; $i < count($spec2); $i++) {
                        $spec3 = $spec3 . '-' . $spec2[$i][0];
                    }
                    $spec3 = substr($spec3, 1);
                    $data['order_detail'][$key]['spec'] = $spec3;
                }
            }
        }
        //排队订单
        if($request['order_type']==2){
            $data = Order::with('Shop')
                ->with('qorder')
                ->where('id',$request['id'])
                ->first();
            if(empty($data)){
                return show(201,'fail');
            }else{
                $data = $data->toArray();
            }
            $type = substr($data['qorder']['number'],0,1);
            //规定用餐时间段
            $before_time = date('Y-m-d H:i:s',strtotime('-1 minute',strtotime($data['qorder']['eat_time'])));
            $after_time = date('Y-m-d H:i:s',strtotime('+1 hour -1 minute',strtotime($data['qorder']['eat_time'])));
            //选择位置不限时
            if($type == 'C'){
                //桌子等待人数
                $desk_waiting = OrderQueue::getWaitingPeople('A',$data,$before_time,$after_time);
                //房间等待人数
                $room_waiting = OrderQueue::getWaitingPeople('B',$data,$before_time,$after_time);
                if($desk_waiting>$room_waiting){
                    $wait_people=$room_waiting;
                }else{
                    $wait_people=$desk_waiting;
                }
                //选择房间或桌子时
            }else {
                //等待人数
                $wait_people = OrderQueue::getWaitingPeople($type,$data,$before_time,$after_time);
            }
            $data['qorder']['wait_people'] = $wait_people;
        }
        if($data['user_id']!=$user_id){
            return show(205,'用户信息不符');
        }

        return show(200,'ok',$data);
    }

    //我的商铺
    public function myShop($token)
    {
        //小程序
        if($token){
            $WeixinUser = WeixinUser::where('token',$token)->first();
            if($WeixinUser){
                $user_id = $WeixinUser['user_id'];
            }else{
                return show(203,'用户不存在');
            }
            //web端
        }else {
            $user_id = Auth::id();
            if (!$user_id) {
                return show(202, '未登录');
            }
        }
        $data = Shop::where('user_id',$user_id)
            ->orderBy('updated_at','desc')
            ->get();
        if(!$data->isEmpty())
        {
            return show(200,'ok',$data);
        }
            return show(201,'empty');
    }

    /*//商家收到的订单
    public function ordersReceived()
    {
        $user_id = Auth::id();
        $data = Shop::with('order')
            ->where('user_id',$user_id)
            ->get();
        if(!$data->isEmpty())
        {
            return show(200,'ok',$data);
        }
            return show(201,'empty');
    }*/

    //充值
    public function recharge()
    {

    }

    //提现
    public function withdraw($request)
    {
        //小程序
        if($request->token){
            $WeixinUser = WeixinUser::where('token',$request->token)->first();
            if(!$WeixinUser){
                return show(204,'请注册后使用');
            }
            $user_id = $WeixinUser['user_id'];
            if ($user_id == '0'){
                return show(203,'请先绑定手机号');
            }

        }else { //web端
            $user_id = Auth::id();
            if (!$user_id) {
                return show(202, '未登录');
            }
            $mUser = User::find($user_id);
            if (!in_array($mUser->role,['2','1'])){
                return show(206,'请先注册成为平台商家');
            }
            $money = $mUser->money;
            if ($money < $request->money){
                return show(201,'提现金额不足');
            }
        }

        $userinfo = UserInfo::where('user_id',$user_id)->first();
        if($userinfo['real_name']==''){
            return show(205,'请先实名认证');
        }
        $id = $request->id;
        //@todo 判断这个提现账户是否属于对应用户
        $cashConfig = CashConfig::where('status',1)->where('user_id',$user_id)->find($id);
        if (!$cashConfig){
            return show(201,'请选择正确的提现账号');
        }
        DB::beginTransaction();
        try{
            $data = array(
                'user_id'=>$user_id,
                'bank'=>$cashConfig->bank,
                'bank_account'=>$cashConfig->account_number,
                'real_name'=>$userinfo['real_name'],
                'money'=>$request->money,
                'cash_status'=>0,
                'created_at'=>date("Y-m-d H:i:s"),
                'updated_at'=>date("Y-m-d H:i:s")
            );
            $resulta = DB::table('cashs')->insert($data);
            $moneychange=new MoneyChange();
            $moneychange=$moneychange->add_money($user_id,$request->money,0,'申请提现',0);
            if($resulta && $moneychange)
            {
                DB::commit();
                return show(200,'申请成功');
            }
        }catch (\Exception $e){
            DB::rollBack();
            return show(203,'申请失败');
        }

     }

}